<template>
  <div class="mt-p-imguploader weui-cell">
    <div class="mt-p-imguploader-add mt-p-imguploader-img" @click="handleAdd">
      <input type="file" 
      @change="onChange" 
      class="mt-p-imguploader-file" 
      ref="file">
      <div class="mt-p-imguploader-pic"></div>
    </div>
    <div class="mt-p-imguploader-img" 
    v-for="(image, index) in images" 
    :key="index">
      <div class="mt-p-imguploader-pic" :style="{backgroundImage: getImageUrl(image)}"></div>
      <div class="mt-p-imguploader-cancel" @click="handleRemove(index)">
        <span>x</span>
      </div>
    </div>
  </div>
</template>

<script>
import Scale from "@/modules/scale"
import { vwToPx } from "@/modules/util"
import axios from "axios"

var uploader = axios.create({
  timeout: 5000
})

export default {
  data() {
    return {
      authKey: "",
      uploaderUrl: "",
      images: [],
      imgs: []
    }
  },
  props: {
    kind: Object
  },
  async mounted() {
    this.init()
  },
  methods: {
    async init() {
      if(!this.imgs.length &&!this.images.length) {
        this.images.push(this.kind.img_view)
        this.imgs.push(this.kind.img)
      }
      this.$emit("changeImage", this.imgs)
      await this.getAuthKey()
    },
    //重置数据
    reset(imgs, images) {
      this.resetFile()
      if (!imgs || !images) {
        this.images = []
        this.imgs = []
      } else {
        this.images = images
        this.imgs = imgs
      }
      setTimeout(()=>{
        this.init()
      },50) //prop在init发生时数据没有发生变化，推迟执行
    },
    handleAdd() {
      this.resetFile()
      this.$refs.file.click()
    },
    resetFile() {
      this.$refs.file.value = ""
    },
    async onChange() {
      let files = this.$refs.file.files[0]
      var formData = await new Scale(files).fileToFormdata()
      await this.uploadImage(formData)
      this.$emit("changeImage", this.imgs)
    },
    async getAuthKey() {
      const { data } = await axios.get("/api/trade/common/getTencentAuth")
      this.uploaderUrl = data.resp_data.uri
      this.authKey = data.resp_data.auth
      return
    },
    async uploadImage(formData) {
      let { data } = await uploader({
        url: this.uploaderUrl,
        method: "post",
        headers: { Authorization: this.authKey },
        data: formData
      })
      if (data.code === 0) {
        this.insertImage(data.data.download_url, data.data.fileid)
      } else {
        throw new Error("fail to upload image")
      }
      return
    },
    insertImage(downloadUrl, fileid) {
      if (this.images.length === 1 && this.images[0] === this.kind.img_view) {
        this.images.splice(0, 1, downloadUrl)
        this.imgs.splice(0, 1, fileid)
      } else {
        this.images.push(downloadUrl)
        this.imgs.push(fileid)
      }
    },
    removeImage(index) {
      this.images.splice(index, 1)
      this.imgs.splice(index, 1)
    },
    handleRemove(index) {
      if (index === 0 && this.images[0] === this.kind.img_view) {
        this.$vux.toast.text("若没有上传图片，系统默认图片无法删除")
      } else if (index === 0 && this.images.length === 1) {
        this.images.splice(0, 1, this.kind.img_view)
        this.imgs.splice(0, 1, this.kind.img)
      } else {
        this.images.splice(index, 1)
        this.imgs.splice(index, 1)
      }
    },
    getImageUrl(path) {
      return `url(${path}?imageView2/1/w/${vwToPx(30)}/h/${vwToPx(22.5)})`
    }
  },
  computed: {
    kindImg() {
      return this.kind.img_view
    }
  }
}
</script>

<style lang="scss">
.mt-p-imguploader {
  padding: 10px 2.5vw;
  font-size: 0 !important;
  display: block !important;

  .mt-p-imguploader-img {
    position: relative;
    display: inline-block;
    width: 30vw;
    height: 22.5vw;
    margin-right: 2vw;
    margin-bottom: 10px;
    vertical-align: middle;

    &:nth-child(3n) {
      margin-right: 0;
    }

    .mt-p-imguploader-pic {
      height: 100%;
      background: none no-repeat scroll center center/cover rgba(0, 0, 0, 0.1);
    }

    .mt-p-imguploader-cancel {
      position: absolute;
      top: -1vw;
      right: -1vw;
      width: 4vw;
      height: 4vw;
      line-height: 4vw;
      font-size: 14px;
      text-align: center;
      color: #fff;
      background-color: red;
      border-radius: 2vw;
    }

    img {
      width: 100%;
    }
  }

  .mt-p-imguploader-add {
    .mt-p-imguploader-pic {
      background-image: url(./ReleaseDeal@2x.png);
    }
    .mt-p-imguploader-file {
      display: none;
    }
  }
}
</style>
